#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <sharp-alloc.h>

/* do-nothing function by default */
static void sharp_alloc_pass(void){
}

static void sharp_alloc_panic(void){
    fprintf(stderr, "Allocation failed! (Out of memory?)");
    abort();
}

static void (*panic)(void) = &sharp_alloc_pass;

void sharp_alloc_init(void (*func)(void)){
    if(!func)
        panic = &sharp_alloc_panic;
    else
        panic = func;
}

void *sharp_malloc(size_t size){
    void *data;

    if((data = malloc(size)) == NULL)
        panic();
    return data;
}

void *sharp_calloc(size_t nmemb, size_t size){
    void *data;

    if((data = calloc(nmemb, size)) == NULL)
        panic();
    return data;
}

void *sharp_realloc(void *data, size_t size){
    void *newdata;

    if((newdata = realloc(data, size)) == NULL)
        panic();
    return newdata;
}

char *sharp_strdup(const char *s){
    char *s2;

    if((s2 = strdup(s)) == NULL)
        panic();
    return s2;
}

char *sharp_strndup(const char *s, size_t n){
    char *s2;

    if((s2 = strndup(s, n)) == NULL)
        panic();
    return s2;
}

